import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { reactive, ref, onMounted } from "vue";
import { isAllEmpty } from "@pureadmin/utils";

export function useGoodsCategory() {
  const form = reactive({
    name: "",
    status: null
  });

  const dataList = ref([]);
  const loading = ref(true);

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      // 模拟API调用，实际项目中应该调用真实的API
      const mockData = [
        {
          id: 1,
          parentId: 0,
          categoryName: "电子产品",
          categoryDesc: "各种电子设备",
          sortValue: 1,
          isShow: true,
          createTime: new Date(),
          children: [
            {
              id: 2,
              parentId: 1,
              categoryName: "手机",
              categoryDesc: "智能手机",
              sortValue: 1,
              isShow: true,
              createTime: new Date()
            }
          ]
        }
      ];

      let newData = mockData;
      if (!isAllEmpty(form.name)) {
        // 前端搜索分类名称
        newData = newData.filter(item => item.categoryName.includes(form.name));
      }
      dataList.value = handleTree(newData); // 处理成树结构
    } catch (error) {
      console.error("获取分类列表失败:", error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 500);
    }
  }

  function handleDelete(row) {
    message(`您删除了分类名称为${row.categoryName}的这条数据`, {
      type: "success"
    });
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 删除部门 */
    handleDelete
  };
}
